#!/usr/bin/evn python3
# -*- coding: utf-8 -*-
from pydub import AudioSegment
from pydub.silence import split_on_silence
from tkinter import *
import sys
import os
from readLrc import readlrc
from audio_play2 import AudioPlay
from pathlib import Path
from utils.oss_util import bucket,httpBaseUrl
from utils.laypage import Laypage
from utils.anki_manage import AnkiManage
import urllib.parse
import tkinter.messagebox #这个是消息框，对话框的关键
from tkinter.filedialog import askdirectory


# 替换main函数中的两个路径，自动创建anki音频，上传至自己的oss，开源前记得换掉oss账号
# http://www.kekenet.com/cet4/tl/
# 发现了获取字幕的好办法lrc。可可英语网站中的公共js变量

#带后缀的将处理文件名
audioName=""

#anki info
deckName="4听力"
modelName="英语听力"

def testMediaPlay(song):
    root = Tk()
    root.geometry('500x500') # 这里的*必须用小写x
    play = AudioPlay(song)
    buttonStart = Button(root, text="play", width="10",command=play.play)
    buttonStart.grid(row=0,column=0)
    buttonStop = Button(root, text="stop", width="10", command=play.stop)
    buttonStop.grid(row=0,column=1)
    root.mainloop()
# 在每一段音频切割前加空腔1秒


def uploadOssAndAnki(sentence):
    global audioName
    global deckName
    global modelName

    #文件名_startTime_endTime_endTime
    fileName= Path(audioName).stem+"_"+str(sentence["startTime"])+"_"+str(sentence["endTime"])+""+Path(audioName).suffix
    # 编码并保存到本地先
    sentence["audioData"].export("chunks\\"+fileName);
    # 上传到阿里云
    htppFileName = os.path.join("english/audio/", fileName)
    res=bucket.put_object_from_file(htppFileName, "chunks\\" + fileName)
    if(res.status!=200):
        tkinter.messagebox.showerror('警告', '上传oss失败')
    # 添加到anki
    print(res)
    # 拼接音频播放url
    audioHttpUrl=httpBaseUrl+urllib.parse.quote(htppFileName)
    enText = sentence["en"]
    chText = sentence["ch"]
    #tags=[Path(audioName).stem]
    ok = AnkiManage.addNote(deckName, modelName, {"audio": audioHttpUrl, "sentence": enText, "translation": chText,
                                                    "source": Path(audioName).stem})
    if(ok):
        tkinter.messagebox.showinfo('提示', '制卡成功')
    else:
        tkinter.messagebox.showerror('错误', '制卡失败，请检查deck、model是否存在')

def createNextPage(root,audioPlay,song,sentences):
    if(sentences==[]):
        return
    values_ = list(root.children.values())
    for tk in values_:
        tk.destroy()

    for i, value in enumerate(sentences):
        time_text = Text(root, width=100, height=3, foreground="green")
        time_text.grid(row=i, column=0, sticky="nw", pady=5)
        time_text.insert(END, value["en"] + "\n" + value["ch"])
        startTime = value["startTime"]
        endTime = value["endTime"] if value["endTime"] != -1 else len(song)
        # 按钮点击就播放一部分音乐
        audioData = song[startTime:endTime]
        # 将切割好的音乐加入实体
        value["audioData"] = audioData

        btn_open = Button(root, text="play", width=10, command=lambda data=audioData: audioPlay.play(data))
        btn_open.grid(row=i, column=1)
        btn_createNote = Button(root, text="addNote", width=10,
                                command=lambda sentence=value: uploadOssAndAnki(sentence))
        btn_createNote.grid(row=i, column=2)
def selectPath(path):
    path_ = askdirectory()
    path.set(path_)
    lrcs= list(Path(path_).glob("*.lrc"))
    if(len(lrcs)!=1):
        tkinter.messagebox.showinfo('错误', '必须有一个lrc文件')
        return
    mp3s= list(Path(path_).glob("*.mp3"))
    if (len(mp3s) != 1):
        tkinter.messagebox.showinfo('错误', '必须有一个lrc文件')
        return

    mp3Path = mp3s[0]
    global audioName
    audioName = os.path.basename(mp3Path)
    lrcPath = lrcs[0]

    if not os.path.exists('./chunks'): os.mkdir('./chunks')
    # 载入
    song = AudioSegment.from_mp3(mp3Path)
    # song = song[:1000*10]
    # song.export('./chunks/'+"test_split.mp3")
    # [(startTime,endTime,enText,chText),()...(999,-1,english,chinese)]
    # 读取歌词文件信息
    sentences = readlrc(lrcPath)
    # testMediaPlay(song)
    createUI(song, sentences)

def createUI(song, sentences):
    laypage = Laypage(sentences,8)

    root2 = Tk()
    frame1 = Frame(root2)
    frame2 = Frame(root2)
    audioPlay = AudioPlay(song)

    #初始化第一页
    createNextPage(frame1,audioPlay,song,laypage.nextList())

    lastPage = Button(frame2, text="lastPage", width=10,
                            command=lambda laypage=laypage: createNextPage(frame1, audioPlay, song, laypage.lastList()))
    lastPage.grid(row=0,column=0);
    nextPage = Button(frame2, text="nextPage", width=10,
                            command=lambda laypage=laypage: createNextPage(frame1,audioPlay,song,laypage.nextList()))
    nextPage.grid(row=0,column=1);

    frame1.grid(row=0);
    frame2.grid(row=1);

    root2.mainloop()
    audioPlay.stop()



def main():
    root = Tk()
    path = StringVar()

    root.title('anki quick')
    Label(root, text="目标路径:").grid(row=0, column=0)
    entry = Entry(root, textvariable=path, width=50)
    entry.grid(row=0, column=1)
    Button(root, text="路径选择", command=lambda path2=path: selectPath(path2)).grid(row=0, column=3)
    root.mainloop()







if __name__ == '__main__':
    main()

